<template>
    <div v-loading="pageLoading" element-loading-text="正在加载创意信息..."
        element-loading-background="rgba(255, 255, 255, 0.8)">
        <!-- 查询表单 -->
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="创意名称" prop="dynamic_creative_name">
                    <el-input class="w-[280px]" v-model="queryParams.dynamic_creative_name" clearable
                        placeholder="请输入创意名称" />
                </el-form-item>
                <el-form-item label="广告主ID" prop="account_id">
                    <el-input class="w-[280px]" v-model="queryParams.account_id" clearable placeholder="请输入广告主ID" />
                </el-form-item>
                <el-form-item label="广告组ID" prop="ad_group_id">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_id" clearable placeholder="请输入广告组ID" />
                </el-form-item>
                <!-- <el-form-item label="广告组名称" prop="ad_group_name">
                    <el-input class="w-[280px]" v-model="queryParams.ad_group_name" clearable placeholder="请输入广告组名称" />
                </el-form-item> -->

                <el-form-item label="创建时间" prop="created_time">
                    <daterange-picker v-model:startTime="queryParams.start_time"
                        v-model:endTime="queryParams.end_time" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 列表卡片 -->
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <el-button v-perms="['ads.tencent_advertising_account/add']" type="primary" @click="handleAdd()">
                <template #icon>
                    <icon name="el-icon-Plus" />
                </template>
                新增
            </el-button>
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column label="ID" prop="id" show-overflow-tooltip width="80" />
                    <el-table-column label="创意名称" prop="dynamic_creative_name" show-overflow-tooltip />
                    <!-- <el-table-column label="广告主ID" prop="account_id" show-overflow-tooltip />
                    <el-table-column label="广告组ID" prop="ad_group_id" show-overflow-tooltip /> -->
                    <el-table-column label="广告组名称" prop="adgroup.ad_group_name" show-overflow-tooltip />
                    <el-table-column label="创意状态" width="120" show-overflow-tooltip>
                        <template #default="{ row }">
                            <el-tag v-if="row.creative_set_approval_status"
                                :type="getStatusType(row.creative_set_approval_status)" size="small">
                                {{ row.creative_set_approval_status }}
                            </el-tag>
                            <span v-else class="text-gray-400">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="create_time" show-overflow-tooltip>
                        <template #default="{ row }">
                            {{ timeFormat(row.create_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" prop="update_time" show-overflow-tooltip>
                        <template #default="{ row }">
                            {{ timeFormat(row.update_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="{ row }">
                            <el-button v-perms="['tencent_ad_creativity/copy']" type="success" link
                                @click="handleCopy(row)">
                                复制
                            </el-button>
                            <el-button v-perms="['tencent_ad_creativity/edit']" type="warning" link
                                @click="handleEdit(row)">
                                编辑
                            </el-button>
                            <el-button v-perms="['tencent_ad_creativity/delete']" type="danger" link
                                @click="handleDelete(row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <!-- 新增/编辑弹窗 -->
        <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑创意信息' : '新增创意信息'" width="70%"
            :before-close="handleClose">
            <el-form :model="formData" ref="formRef" label-width="120px" class="space-y-4">
                <!-- ID字段(编辑时显示) -->
                <el-form-item v-if="formData.id">
                    <el-input v-model="formData.id" disabled style="display: none;"></el-input>
                </el-form-item>

                <!-- 创意名称和状态 -->
                <el-form-item label="创意名称" prop="name">
                    <div class="flex items-center gap-3">
                        <el-input v-model="formData.name" placeholder="请输入创意名称" class="w-[300px]"></el-input>
                        <el-tag v-if="formData.id && formData.creative_set_approval_status"
                            :type="getEditStatusType(formData.creative_set_approval_status)" size="large"
                            class="text-base font-semibold">
                            {{ getStatusText(formData.creatives_status) }}
                        </el-tag>
                    </div>
                </el-form-item>

                <div class="grid grid-cols-2 gap-4">
                    <!-- 账号选择 -->
                    <el-form-item label="账号" prop="accountId">
                        <el-select v-model="formData.accountId" placeholder="请选择账号" @focus="loadAccounts"
                            @change="handleAccountChange">
                            <el-option v-for="account in accounts" :key="account.id"
                                :label="`${account.account_name}【 账号:${account.account_id}】`"
                                :value="account.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 广告组选择 -->
                    <el-form-item label="广告组" prop="ad_group_id">
                        <el-select v-model="formData.ad_group_id" placeholder="请选择广告组" :disabled="!formData.accountId">
                            <el-option v-for="group in adGroups" :key="group.id"
                                :label="`${group.corporation_name} 【${group.ad_group_name}】`"
                                :value="String(group.ad_group_id)"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 落地页类型选择 -->
                    <el-form-item label="落地页类型" prop="page_type">
                        <el-radio-group v-model="formData.page_type" @change="handlePageTypeChange">
                            <el-radio label="1">官方落地页</el-radio>
                            <el-radio label="2">微信客服</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <!-- 官方落地页选择，改为多选 -->
                    <el-form-item v-if="formData.page_type === '1'" label="官方落地页" prop="landingPageId">
                        <el-select v-model="formData.landingPageId" placeholder="请选择落地页" :multiple-limit=3
                            :disabled="!formData.accountId" multiple>
                            <el-option v-for="page in landingPages" :key="page.page_id" :label="page.page_name"
                                :value="page.page_id" :loading="loadingPage"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 微信客服链接输入 -->
                    <el-form-item v-if="formData.page_type === '2'" label="微信客服" prop="wechat_consult_id">

                        <el-select v-model="formData.wechat_consult_id" placeholder="请选择微信客服">
                            <el-option v-for="item in wechat_consult_options" :key="item.id" :label="item.nickname"
                                :value="item.id" />
                        </el-select>


                        <!-- <el-input v-model="formData.wechat_consult_id" placeholder="请输入微信客服链接"
                            :disabled="!formData.accountId"></el-input> -->
                    </el-form-item>

                    <!-- 品牌选择，改为多选 -->
                    <el-form-item label="品牌" prop="brand_id">
                        <el-select v-model="formData.brand_id" :disabled="!formData.accountId" :multiple-limit=3
                            placeholder="请选择品牌" multiple>
                            <el-option v-for="brand in brands" :key="brand.image_id" :label="brand.name"
                                :value="brand.image_id"></el-option>
                        </el-select>
                    </el-form-item>
                </div>

                <el-form-item label="文案">
                    <div class="w-full">
                        <!-- 只需要一个flex容器 -->
                        <!-- <div class="mb-4 mr-3">
                            <el-button type="primary" size="small" @click="addCopywriting"
                                :disabled="formData.copywritingList.length === 3">
                                <el-icon>
                                    <Plus />
                                </el-icon> 添加文案
                            </el-button>
                        </div> -->

                        <!-- 文案输入框组 -->
                        <div v-for="(item, index) in formData.copywritingList" :key="index"
                            class="flex items-center justify-center mb-4 mr-2">
                            <el-input v-model="item.content" placeholder="请输入文案内容,30字以内" class="flex-1"
                                clearable></el-input>

                            <el-tooltip content="AI智能仿写，基于当前文案生成优化版本" placement="top" :show-after="500">
                                <el-button type="primary" size="small" class="ai-copywriting-btn ml-2"
                                    @click="aiCopywriting(index)" :loading="aiLoadingStates[index]"
                                    :disabled="item.content.length === 0">
                                    <el-icon class="ai-icon">
                                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                                            <path
                                                d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" />
                                        </svg>
                                    </el-icon>
                                    <span class="ai-text">AI仿写</span>
                                </el-button>
                            </el-tooltip>
                            <el-button type="danger" @click="removeCopywriting(index)"
                                :disabled="formData.copywritingList.length === 1" class="ml-2">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </div>

                        <div class="add-btn flex items-center justify-center mb-4 mr-2" @click="addCopywriting">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <span class="ml-2">添加文案</span>
                        </div>

                        <!-- 历史文案选择模块 -->
                        <div class="history-copywriting-section">
                            <div class="section-header">
                                <h4 class="section-title">
                                    <el-icon class="history-icon">
                                        <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16">
                                            <path
                                                d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z" />
                                        </svg>
                                    </el-icon>
                                    历史文案
                                </h4>
                                <!-- <el-button type="text" size="small" @click="refreshHistoryCopywriting"
                                    :loading="historyLoading" class="refresh-btn">
                                    <el-icon><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14">
                                            <path
                                                d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
                                        </svg></el-icon>
                                    刷新
                                </el-button> -->
                            </div>

                            <div class="history-cards-container">
                                <div v-for="(copywriting, index) in historyPager.lists" :key="index"
                                    class="history-card" :class="{ 'selected': selectedHistoryIndex === index }"
                                    @click="selectHistoryCopywriting(index)">
                                    <div class="card-content">
                                        <div class="copywriting-text">{{ copywriting.content}}</div>
                                        <div class="card-actions">
                                            <el-button type="primary" size="small"
                                                @click.stop="useHistoryCopywriting(index)" class="use-btn">
                                                使用
                                            </el-button>
                                            <el-button type="success" size="small" @click.stop="aiRewriteHistory(index)"
                                                :loading="aiRewriteLoading === index" class="rewrite-btn">
                                                <el-icon class="ai-icon-small">
                                                    <svg viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                                                        <path
                                                            d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" />
                                                    </svg>
                                                </el-icon>
                                                仿写
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 历史文案分页 -->
                            <div v-if="historyPager.count > 0" class="history-pagination-container">
                                <pagination v-model="historyPager" @change="getHistoryCopywriting" />
                            </div>

                            <div v-if="historyPager.lists.length === 0 && !historyPager.loading" class="empty-state">
                                <el-icon class="empty-icon">
                                    <svg viewBox="0 0 24 24" fill="currentColor" width="48" height="48">
                                        <path
                                            d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-5 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" />
                                    </svg>
                                </el-icon>
                                <p class="empty-text">暂无历史文案</p>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="图片素材：" prop="imageList">
                    <div class="flex items-start gap-4">
                        <material-picker v-model="formData.imageList" :limit="5" />
                        <div class="text-[#F56C6C] text-sm flex-shrink-0" style="min-width: 300px;">
                            <div>提示：图片尺寸仅支持</div>
                            <div class="flex flex-wrap gap-2">
                                <span>• 3:2 (480X320, ≤400K)</span>
                                <span>• 20:7 (960X334, ≤400K)</span>
                                <span>• 9:16 (1080X1920, ≤400K)</span>

                            </div>
                            <div class="flex flex-wrap gap-2">
                                <span>• 1:1 (800X800, ≤400K)</span>
                                <span>• 16:9 (1280X720, ≤400K)</span>
                            </div>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="视频素材：" prop="videoList">
                    <div class="flex items-start gap-4">
                        <material-picker v-model="formData.videoList" :limit="3" type="video" />
                        <div class="text-[#F56C6C] text-sm flex-shrink-0" style="min-width: 300px;">
                            <div>提示：视频尺寸仅支持</div>
                            <div class="flex flex-wrap gap-2">
                                <span>• 16:9 (最小1280X720, 5~30s, ≤500M)</span>
                                <span>• 4:3 (1280X960, 5~300s, ≤500M)</span>
                                <span>• 16:9 (最小1280X720, 5~300s, ≤500M)</span>

                            </div>
                            <div class="flex flex-wrap gap-2">
                                <span>• 9:16 (最小1080X1920, 5~5s, ≤500M)</span>
                                <span>• 9:16 (最小720X1280, 5~300s, ≤500M)</span>
                            </div>
                        </div>
                    </div>
                </el-form-item>

            </el-form>

            <template #footer>
                <div class="flex justify-end space-x-3">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveForm">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 选择广告组对话框 -->
        <el-dialog v-model="adGroupDialogVisible" title="选择广告组" width="30%" :before-close="handleAdGroupDialogClose">
            <el-form>
                <!-- 新增创意名称输入框 -->
                <el-form-item label="创意名称">
                    <el-input v-model="copyCreativeName" placeholder="请输入创意名称"></el-input>
                </el-form-item>
                <el-form-item label="广告组">
                    <el-select v-model="selectedAdGroupId" placeholder="请选择广告组">
                        <el-option v-for="adGroup in adGroupList" :key="adGroup.id"
                            :label="`${adGroup.corporation_name} -- ${adGroup.ad_group_name}`"
                            :value="adGroup.ad_group_id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="flex justify-end space-x-3">
                    <el-button @click="adGroupDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmCopy">确认</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { usePaging } from '@/hooks/usePaging';
import { useRoute } from 'vue-router';
import {
    apiTencentAdCreativityList,
    apiTencentAdCreativityAdd,
    apiTencentAdCreativityEdit,
    apiTencentAdCreativityCopy,
    apiGetAdCreatives,
    apiGetLandingPages,
    apiGetAccounts,
    apiGetBrands,
    apiTencentAdCreativityDelete,
    apiGetDynamicCreativeDetail
} from '@/api/tencent_ad_creativity';
import {
    ElLoading,
    ElMessage,
    ElMessageBox,
    type ElMessageBoxOptions,
    ElNotification
} from 'element-plus'
import { timeFormat } from '@/utils/util';
import feedback from '@/utils/feedback';
import {
    apiTencentAdvertisingUserAdListLists, selectList, getAiTitle, get_history_copywriting
} from '@/api/tencent_advertising_user_ad_list'
import { Plus, Delete } from '@element-plus/icons-vue'

// 查询条件
const queryParams = reactive({
    dynamic_creative_name: '',
    start_time: '',
    end_time: '',
    account_id: '',
    ad_group_id: '',
    ad_group_name: ''
});
// 新增创意名称变量
const copyCreativeName = ref('');
// 选中数据
const selectData = ref<any[]>([]);

// 路由实例
const route = useRoute();

// 分页相关
const { pager, getLists: originalGetLists, resetParams, resetPage } = usePaging({
    fetchFun: apiTencentAdCreativityList,
    params: queryParams
});

// 使用原始的getLists函数
const getLists = originalGetLists;

// 新增、编辑弹窗
const dialogVisible = ref(false);
const formRef = ref(null);
const loadingPage = ref(false);
const formData = ref({
    id: '',
    name: '',
    page_type: '1', // 落地页类型：1官方落地页 2微信客服
    landingPageId: '',
    wechat_consult_id: '', // 微信客服链接
    ad_group_id: '',
    accountId: '',
    brand: [{ brand_name: "", brand_image_id: "" }],
    brand_id: [],
    copywritingList: [{ "content": "" }],
    imageList: [],
    videoList: [],
    tenant_id: '',
    account_id: '',
    dynamic_creative_id: '',
    creatives_status: '', // 创意状态
    creative_set_approval_status: '' // 创意状态
});

// 图片预览相关
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');
const accountIdBy = ref('');
// 选择广告组对话框
const adGroupDialogVisible = ref(false);
const selectedAdGroupId = ref('');
const adGroupList = ref<any[]>([]);
const adGroups = ref<any[]>([]);
let currentCopyRow = ref<any>(null);

// 官方落地页列表
const landingPages = ref<any[]>([]);
// 账号列表
const accounts = ref<any[]>([]);
// 品牌列表
const brands = ref<any[]>([]);

const wechat_consult_options = ref<any[]>([]);

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id);
};

// 新增
const handleAdd = () => {
    dialogVisible.value = true;
    formData.value = {
        id: '',
        name: '',
        page_type: '1', // 落地页类型：1官方落地页 2微信客服
        landingPageId: '',
        wechat_consult_id: '', // 微信客服链接
        ad_group_id: '',
        accountId: '',
        brand: [{ brand_name: "", brand_image_id: "" }],
        brand_id: [],
        copywritingList: [{ "content": "" }],
        imageList: [],
        videoList: [],
        tenant_id: '',
        account_id: '',
        dynamic_creative_id: '',
        creatives_status: '',
        creative_set_approval_status: ''
    };
};

// 编辑
const handleEdit = async (row: any) => {
    const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在获取创意详情...',
        background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
        // 获取创意详情
        const detailResponse = await apiGetDynamicCreativeDetail({
            account_id: row.account_id,
            dynamic_creative_id: row.dynamic_creative_id
        });

        const detailData = detailResponse;

        // 设置账号ID，用于加载相关数据
        accountIdBy.value = detailData.account_id;

        // 加载账号相关的数据
        await loadAccounts();
        await loadAdGroups({ account_id: detailData.account_id });
        await loadLandingPages();
        await loadBrands();

        // 填充表单数据
        formData.value = {
            id: row.id,
            name: detailData.name,
            page_type: detailData.page_type || '1',
            landingPageId: detailData.landingPageId || [],
            wechat_consult_id: detailData.wechat_consult_id || '',
            ad_group_id: String(detailData.ad_group_id),
            accountId: accounts.value.find(acc => acc.account_id === detailData.account_id)?.id || '',
            brand: detailData.brand || [],
            brand_id: detailData.brand_id || [],
            copywritingList: detailData.copywritingList || [{ "content": "" }],
            imageList: detailData.imageList || [],
            videoList: detailData.videoList || [],
            tenant_id: row.tenant_id,
            account_id: detailData.account_id,
            dynamic_creative_id: detailData.dynamic_creative_id,
            creatives_status: detailData.creatives_status || '',
            creative_set_approval_status: detailData.creative_set_approval_status || ''
        };

        // 调试信息
        console.log('详情数据中的广告组ID:', detailData.ad_group_id, '类型:', typeof detailData.ad_group_id);
        console.log('广告组列表:', adGroups.value);
        console.log('匹配的广告组:', adGroups.value.find(group =>
            group.ad_group_id === detailData.ad_group_id ||
            group.ad_group_id === String(detailData.ad_group_id) ||
            String(group.ad_group_id) === detailData.ad_group_id
        ));

        dialogVisible.value = true;

    } catch (error) {
        console.error('获取创意详情失败:', error);
        feedback.msgError('获取创意详情失败');
    } finally {
        loadingInstance?.close();
    }
};
const handleDelete = async (row: any) => {
    const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    try {
        await ElMessageBox.confirm('确认要删除该创意吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        await apiTencentAdCreativityDelete({
            account_id: row.account_id,
            dynamic_creative_id: row.dynamic_creative_id
        });
        feedback.msgSuccess('删除成功');
        getLists();
    } catch (error) {
        if (error !== 'cancel') {
            feedback.msgError('删除失败');
        }
    } finally {
        loadingInstance?.close();
    }
};


// 关闭选择广告组对话框
const handleAdGroupDialogClose = () => {
    adGroupDialogVisible.value = false;
    selectedAdGroupId.value = '';
};

// 账号选择变化时触发
const handleAccountChange = (accountId: string) => {
    // 清空之前选择的广告组、落地页和品牌
    const selectedAccount = accounts.value.find(account => account.id === accountId);
    if (!selectedAccount) {
        ElMessage.warning('未找到所选账号信息');
        return;
    }
    formData.value.landingPageId = ''; // 清空落地页(多选)
    formData.value.brand = []; // 清空品牌(多选)
    formData.value.brand_id = [];
    formData.value.ad_group_id = '';
    accountIdBy.value = selectedAccount.account_id;
    adGroups.value = [];
    landingPages.value = [];
    brands.value = [];

    // 如果选择了账号，则加载对应的广告组、落地页和品牌
    if (accountId) {
        loadAdGroups({ account_id: selectedAccount.account_id });
        loadLandingPages();
        loadBrands();
    }
};

// 落地页类型变化时触发
const handlePageTypeChange = (pageType: string | number | boolean | undefined) => {
    if (pageType === '1') {
        // 选择官方落地页时，清空官方落地页选择
        formData.value.landingPageId = '';
    } else if (pageType === '2') {
        // 选择微信客服时，清空官方落地页选择
        formData.value.landingPageId = '';
    }
};

// 获取状态类型（用于列表显示）
const getStatusType = (status: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
    const statusMap: { [key: string]: 'success' | 'warning' | 'info' | 'primary' | 'danger' } = {
        '投放中': 'success',
        '部分投放中': 'success',
        '未知': 'info'
    };
    return statusMap[status] || 'info';//部分投放中
};

// 获取编辑时的状态类型（用于编辑弹窗）
const getEditStatusType = (status: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
    const statusMap: { [key: string]: 'success' | 'warning' | 'info' | 'primary' | 'danger' } = {
        'CREATIVE_SET_APPROVAL_STATUS_NORMAL': 'success',
        'CREATIVE_SET_APPROVAL_STATUS_PENDING': 'warning',
        'CREATIVE_SET_APPROVAL_STATUS_REJECTED': 'danger',
        'CREATIVE_SET_APPROVAL_STATUS_DISAPPROVED': 'danger'
    };
    return statusMap[status] || 'info';
};

// 获取状态文本（用于编辑弹窗）
const getStatusText = (status: string) => {
    return status;
};



// 加载广告组列表
const loadAdGroups = async (params: { account_id: string; tenant_id?: string }) => {
    try {
        // 构建请求参数
        const query = {
            account_id: params.account_id,
            page_size: 99
        };

        // 记录请求参数（用于调试）
        console.log('请求广告组列表参数:', query);

        // 显示加载状态
        loadingPage.value = true;

        // 执行API请求
        const response = await apiTencentAdvertisingUserAdListLists(query);

        // 校验响应数据格式
        if (response && Array.isArray(response.lists)) {
            adGroups.value = response.lists;
            console.log(`成功加载 ${response.lists.length} 个广告组`);
            console.log('广告组数据结构:', response.lists[0]); // 查看第一个广告组的数据结构
        } else {
            throw new Error('广告组列表数据格式不正确');
        }
    } catch (error) {
        // 统一错误处理
        const errorMessage =
            error instanceof Error
                ? error.message
                : '获取广告组列表失败: 未知错误';

        console.error('获取广告组列表失败:', errorMessage);
        feedback.msgError(errorMessage);
    } finally {
        // 隐藏加载状态（无论成功或失败）
        loadingPage.value = false;
    }
};

// 加载账号列表
const loadAccounts = async () => {
    try {
        const response = await apiGetAccounts({ "account_role_type": "ACCOUNT_ROLE_TYPE_ADVERTISER", page_size: 999 });
        console.log(response, 'responseresponseresponse');
        accounts.value = response.list;
    } catch (error) {
        feedback.msgError('获取账号列表失败');
    }
};

// 加载品牌列表
const loadBrands = async () => {
    try {
        const response = await apiGetBrands({ account_id: accountIdBy.value, page_size: 99 });
        brands.value = response;
    } catch (error) {
        feedback.msgError('获取品牌列表失败');
    }
};

// 加载官方落地页列表
const loadLandingPages = async () => {
    try {
        loadingPage.value = true;
        const response = await apiGetLandingPages({ account_id: accountIdBy.value, page_size: 99 });
        landingPages.value = response;
    } catch (error) {
        feedback.msgError('获取官方落地页列表失败');
    } finally {
        loadingPage.value = false;
    }
};

const handleClose = () => {
    console.log(111);
    dialogVisible.value = false;
};

// 确认选择广告组

const handleAdGroupConfirm = () => {
    // 处理选择逻辑
    if (selectedAdGroupId.value) {
        formData.value.ad_group_id = selectedAdGroupId.value;
        handleAdGroupDialogClose();
    } else {
        ElMessage.warning('请选择一个广告组');
    }
};

// 确认复制
const confirmCopy = async () => {
    if (!selectedAdGroupId.value) {
        feedback.msgError('请选择一个广告组');
        return;
    }
    if (!copyCreativeName.value) {
        feedback.msgError('请输入创意名称');
        return;
    }
    try {
        await feedback.confirm(`确定要从【${currentCopyRow.value.adgroup.ad_group_name}】复制该创意到广告组【${selectedAdGroupId.value}】吗?`);
        const copyParams = {
            ad_group_id: selectedAdGroupId.value,
            id: currentCopyRow.value.id,
            account_id: currentCopyRow.value.account_id,
            // 新增创意名称字段
            name: copyCreativeName.value
        };

        const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在复制创意...',
            background: 'rgba(0, 0, 0, 0.7)'
        });

        try {
            await apiTencentAdCreativityCopy(copyParams)
                .then(() => {
                    feedback.msgSuccess('复制成功,获取创意数据需等待几秒，然后刷新页面！');
                    loadingInstance.close();
                    adGroupDialogVisible.value = false;
                    copyCreativeName.value = ''; // 清空创意名称输入框
                    return new Promise(resolve => setTimeout(resolve, 5000));
                })
                .then(() => {
                    return apiGetAdCreatives({ account_id: currentCopyRow.value.account_id });
                })
                .then(response => {
                    getLists();
                })
                .catch(error => {
                    console.error('操作链发生错误:', error.response.data.message);
                    ElMessage.error({
                        message: error.response.data.message,
                        duration: 15000
                    });
                });
        } catch (error) {
            feedback.msgError('复制失败');
        } finally {
            loadingInstance.close();
        }
    } catch (error) {
        feedback.msgError('复制失败');
    }
};

// 添加文案
const addCopywriting = () => {
    if (formData.value.copywritingList.length < 3) {
        formData.value.copywritingList.push({ content: '' });
    } else {
        ElMessage.warning('最多添加3个文案');
    }
};

// 删除文案
const removeCopywriting = (index: number) => {
    formData.value.copywritingList.splice(index, 1);
};

// 复制
const handleCopy = async (row: any) => {
    currentCopyRow.value = row;
    try {
        const param_q = {
            "tenant_id": row.tenant_id,
            "account_id": row.account_id
        };
        const response = await apiTencentAdvertisingUserAdListLists(param_q);
        adGroupList.value = response.lists;
        if (adGroupList.value.length > 0) {
            selectedAdGroupId.value = adGroupList.value[0].ad_group_id;
        }
        copyCreativeName.value = row.dynamic_creative_name + " copy";
        adGroupDialogVisible.value = true;
    } catch (error) {
        feedback.msgError('获取广告组列表失败');
    }
};

// 保存表单
const saveForm = async () => {
    const formDataToSend = { ...formData.value };
    formDataToSend.account_id = accountIdBy.value;

    // 如果是编辑模式，确保包含dynamic_creative_id
    if (formDataToSend.id) {
        formDataToSend.dynamic_creative_id = formData.value.dynamic_creative_id;
    }

    // 转换品牌数据
    const brandIds = formData.value.brand_id || [];
    // 转换品牌数据
    const selectedBrands = brandIds.map(brandId => {
        // 从原始品牌列表中查找匹配的品牌，详情接口的brand_id对应品牌接口的image_id
        const brand = brands.value.find(item =>
            item.image_id === brandId ||
            item.image_id === String(brandId)
        );
        return {
            brand_name: brand?.name || '',
            brand_image_id: brand?.image_id || String(brandId)
        };
    });
    formDataToSend.brand = selectedBrands;
    console.log(formDataToSend, 'formDataToSend')
    const loadingInstanceCreatives = ElLoading.service({
        lock: true,
        text: formDataToSend.id ? '正在更新创意...' : '正在创建创意...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    try {

        if (formDataToSend.id) {
            // 编辑保存
            await apiTencentAdCreativityEdit(formDataToSend)
                .then(() => {
                    feedback.msgSuccess('编辑成功,更新创意数据需等待几秒，然后刷新页面！');
                    dialogVisible.value = false;
                    return new Promise(resolve => setTimeout(resolve, 4000));
                })
                .then(() => {
                    return apiGetAdCreatives({ account_id: formDataToSend.account_id });
                })
                .then(response => {
                    getLists();
                })
                .catch(error => {
                    console.error('操作链发生错误:', error.response.data.message);
                    ElMessage.error({
                        message: error.response.data.message,
                        duration: 15000
                    });
                });
        } else {
            // 新增保存
            await apiTencentAdCreativityAdd(formDataToSend)
                .then(() => {
                    feedback.msgSuccess('创建成功,更新创意数据需等待几秒，然后刷新页面！');
                    dialogVisible.value = false;
                    return new Promise(resolve => setTimeout(resolve, 4000));
                })
                .then(() => {
                    return apiGetAdCreatives({ account_id: formDataToSend.account_id });
                })
                .then(response => {
                    getLists();
                })
                .catch(error => {
                    console.error('操作链发生错误:', error.response.data.message);
                    ElMessage.error({
                        message: error.response.data.message,
                        duration: 15000
                    });
                });
        }

    } catch (error) {
        console.log(error, 'errorerrorerrorerrorerror');
        feedback.msgError('保存失败');
    } finally {
        // 确保无论成功还是失败都会关闭加载状态
        loadingInstanceCreatives.close();
    }
};

// 页面加载状态
const pageLoading = ref(false);

// AI仿写加载状态
const aiLoadingStates = ref<{ [key: number]: boolean }>({});

// 历史文案相关状态
const historyCopywritingList = ref<string[]>([]);
const selectedHistoryIndex = ref<number>(-1);
const historyLoading = ref<boolean>(false);
const aiRewriteLoading = ref<number>(-1);

// 历史文案分页状态
const historyPager = reactive({
    page: 1,
    size: 15, // 每页显示6个，适合网格布局
    count: 0,
    loading: false,
    lists: [] as any[]
});

// AI仿写函数
const aiCopywriting = async (index: number) => {
    try {
        // 设置加载状态
        aiLoadingStates.value[index] = true;

        // 获取当前文案内容作为参考
        const currentContent = formData.value.copywritingList[index]?.content || '';

        let res;
        try {
            res = await getAiTitle({ content: currentContent, nums: 1 });
        } catch (error) {
            console.error('AI接口调用失败:', error);
            throw new Error('AI服务暂时不可用');
        }

        // 处理AI响应结果
        let aiGeneratedContent = '';
        if (res && res.length > 0) {
            // 获取AI生成的文案
            aiGeneratedContent = res[0];
            // 确保文案长度不超过30字
            if (aiGeneratedContent.length > 30) {
                aiGeneratedContent = aiGeneratedContent.substring(0, 30);
            }
        } else {
            // 如果AI接口返回失败，使用默认优化
            aiGeneratedContent = `${currentContent} - 限时优惠，立即抢购！`;
            if (aiGeneratedContent.length > 30) {
                aiGeneratedContent = aiGeneratedContent.substring(0, 30);
            }
        }

        // 更新文案内容
        formData.value.copywritingList[index].content = aiGeneratedContent;

        ElMessage.success('AI仿写完成！');
    } catch (error) {
        console.error('AI仿写失败:', error);
        // 如果AI服务失败，使用本地优化
        const currentContent = formData.value.copywritingList[index]?.content || '';
        const fallbackContent = `${currentContent} - 限时优惠，立即抢购！`;
        formData.value.copywritingList[index].content = fallbackContent.substring(0, 30);
        ElMessage.warning('AI服务暂时不可用，已使用本地优化');
    } finally {
        // 清除加载状态
        aiLoadingStates.value[index] = false;
    }
};


// 选择历史文案
const selectHistoryCopywriting = (index: number) => {
    selectedHistoryIndex.value = index;
};

// 使用历史文案
const useHistoryCopywriting = (index: number) => {
    const selectedCopywriting = historyPager.lists[index].content;
    if (selectedCopywriting) {
        // 添加到当前文案列表
        if (formData.value.copywritingList.length < 3) {
            formData.value.copywritingList.push({ content: selectedCopywriting });
            ElMessage.success('已添加历史文案');
        } else {
            ElMessage.warning('最多只能添加3个文案');
        }
    }
};

// AI重写历史文案
const aiRewriteHistory = async (index: number) => {
    try {
        aiRewriteLoading.value = index;
        const originalCopywriting = historyPager.lists[index].content;

        // 调用AI接口进行重写
        let res;
        try {
            res = await getAiTitle({ content: originalCopywriting, nums: 1 });
        } catch (error) {
            console.error('AI接口调用失败:', error);
            throw new Error('AI服务暂时不可用');
        }

        // 处理AI响应结果
        let optimizedCopywriting = '';
        if (res && res.length > 0) {
            // 获取AI生成的文案
            optimizedCopywriting = res[0];

            // 确保文案长度不超过30字
            if (optimizedCopywriting.length > 30) {
                optimizedCopywriting = optimizedCopywriting.substring(0, 30);
            }
        } else {
            // 如果AI接口返回失败，使用默认优化
            optimizedCopywriting = `${originalCopywriting} - 限时抢购，错过再等一年！`;
            if (optimizedCopywriting.length > 30) {
                optimizedCopywriting = optimizedCopywriting.substring(0, 30);
            }
        }

        // 更新历史文案列表
        historyPager.lists[index] = { ...historyPager.lists[index], content: optimizedCopywriting };

        ElMessage.success('AI重写完成！');
    } catch (error) {
        console.error('AI重写失败:', error);
        ElMessage.error('AI重写失败，请重试');
    } finally {
        aiRewriteLoading.value = -1;
    }
};

const getSelectList = async () => {
    let res = await selectList()
    if (res) {
        wechat_consult_options.value = res
        console.log(res, '1111111111111111');
    }
}

const getHistoryCopywriting = async () => {
    historyPager.loading = true;
    try {
        let res = await get_history_copywriting({
            page_no: historyPager.page,
            page_size: historyPager.size
        });
        console.log(res, '历史文案分页数据');
        if (res && res.lists) {
            historyPager.lists = res.lists;
            historyPager.count = res.count || 0;
        } else {
            historyPager.lists = [];
            historyPager.count = 0;
        }
    } catch (error) {
        console.error('获取历史文案失败:', error);
        historyPager.lists = [];
        historyPager.count = 0;
    } finally {
        historyPager.loading = false;
    }
};

// 页面加载时检查路由参数
onMounted(() => {
    // 检查是否从广告组页面跳转过来
    const fromAdGroup = route.query.from_ad_group;
    const editMode = route.query.edit_mode;
    const addMode = route.query.add_mode;

    if (fromAdGroup === 'true') {
        // 设置加载状态，防止重复点击
        pageLoading.value = true;

        if (editMode === 'true') {
            // 编辑模式：加载创意详情
            handleEditWithAdGroupInfo().finally(() => {
                pageLoading.value = false;
            });
        } else if (addMode === 'true') {
            // 新增模式：自动打开新增弹框并填充广告组信息
            handleAddWithAdGroupInfo().finally(() => {
                pageLoading.value = false;
            });
        } else {
            pageLoading.value = false;
        }
    }

    getSelectList()
    getHistoryCopywriting()
});

// 带广告组信息的编辑方法
const handleEditWithAdGroupInfo = async () => {
    try {
        // 获取路由参数中的创意ID和广告组信息
        const creativeId = route.query.id as string;
        const dynamicCreativeId = route.query.dynamic_creative_id as string;
        const adGroupId = route.query.ad_group_id as string;
        const adGroupName = route.query.ad_group_name as string;
        const accountId = route.query.account_id as string;
        const adAccountId = route.query.ad_account_id as string;
        const corporationName = route.query.corporation_name as string;

        if (!creativeId) {
            ElMessage.error('缺少创意ID参数');
            return;
        }

        if (!accountId) {
            ElMessage.error('缺少广告主ID参数');
            return;
        }

        // 设置账号ID
        accountIdBy.value = accountId;

        // 加载相关数据
        await loadAccounts();
        await loadAdGroups({ account_id: accountId });
        await loadLandingPages();
        await loadBrands();

        // 加载创意详情 - 使用dynamic_creative_id和account_id
        const detailData = await apiGetDynamicCreativeDetail({
            dynamic_creative_id: dynamicCreativeId || creativeId,
            account_id: accountId
        });

        if (detailData) {
            // 打开编辑弹框
            dialogVisible.value = true;

            // 填充表单数据 - 与handleEdit方法保持一致
            formData.value = {
                id: creativeId,
                name: detailData.name || `${adGroupName}_创意`,
                page_type: detailData.page_type || '1',
                landingPageId: detailData.landingPageId || [],
                wechat_consult_id: detailData.wechat_consult_id || '',
                ad_group_id: String(detailData.ad_group_id || adGroupId),
                accountId: accounts.value.find(acc => acc.account_id === accountId)?.id || '',
                brand: detailData.brand || [],
                brand_id: detailData.brand_id || [],
                copywritingList: detailData.copywritingList || [{ "content": "" }],
                imageList: detailData.imageList || [],
                videoList: detailData.videoList || [],
                tenant_id: detailData.tenant_id || '',
                account_id: accountId,
                dynamic_creative_id: detailData.dynamic_creative_id || dynamicCreativeId || '',
                creatives_status: detailData.creatives_status || '',
                creative_set_approval_status: detailData.creative_set_approval_status || ''
            };

            // 调试信息
            console.log('详情数据中的广告组ID:', detailData.ad_group_id, '类型:', typeof detailData.ad_group_id);
            console.log('广告组列表:', adGroups.value);
            console.log('匹配的广告组:', adGroups.value.find(group =>
                group.ad_group_id === detailData.ad_group_id ||
                group.ad_group_id === String(detailData.ad_group_id) ||
                String(group.ad_group_id) === detailData.ad_group_id
            ));

            // 显示成功消息
            ElMessage.success(`已加载创意详情：${detailData.name || '创意详情'}`);
        } else {
            ElMessage.error('获取创意详情失败');
        }

    } catch (error) {
        console.error('加载创意详情失败：', error);
        ElMessage.error('加载创意详情失败，请手动编辑');
    }
};

// 带广告组信息的新增方法
const handleAddWithAdGroupInfo = async () => {
    try {
        // 获取路由参数中的广告组信息
        const adGroupId = route.query.ad_group_id as string;
        const adGroupName = route.query.ad_group_name as string;
        const accountId = route.query.account_id as string;
        const adAccountId = route.query.ad_account_id as string;
        const corporationName = route.query.corporation_name as string;

        // 设置账号ID
        accountIdBy.value = accountId;

        // 加载相关数据
        await loadAccounts();
        await loadAdGroups({ account_id: accountId });
        await loadLandingPages();
        await loadBrands();

        // 打开新增弹框
        dialogVisible.value = true;

        // 填充表单数据
        formData.value = {
            id: '',
            name: `${adGroupName}_创意`,
            page_type: '1',
            landingPageId: '',
            wechat_consult_id: '',
            ad_group_id: adGroupId,
            accountId: accounts.value.find(acc => acc.account_id === accountId)?.id || '',
            brand: [{ brand_name: "", brand_image_id: "" }],
            brand_id: [],
            copywritingList: [{ "content": "" }],
            imageList: [],
            videoList: [],
            tenant_id: '',
            account_id: accountId,
            dynamic_creative_id: '',
            creatives_status: '',
            creative_set_approval_status: ''
        };

        // 显示成功消息
        ElMessage.success(`已自动填充广告组信息：${adGroupName}`);

    } catch (error) {
        console.error('自动填充广告组信息失败：', error);
        ElMessage.error('自动填充广告组信息失败，请手动选择');
        // 如果自动填充失败，仍然打开新增弹框
        handleAdd();
    }
};

getLists();
</script>

<style scoped>
.add-btn {
    padding: 2px;
    border: 1px dashed #dcdfe6;
    border-radius: 5px;
}

/* AI仿写按钮样式 */
.ai-copywriting-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 12px;
    padding: 8px 16px;
    font-weight: 600;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
    position: relative;
    overflow: hidden;
    min-width: 100px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.ai-copywriting-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
}

.ai-copywriting-btn:hover::before {
    left: 100%;
}

.ai-copywriting-btn:hover {
    transform: translateY(-2px) scale(1.02);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.35);
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.ai-copywriting-btn:active {
    transform: translateY(0) scale(0.98);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
}

.ai-copywriting-btn .ai-icon {
    margin-right: 6px;
    animation: aiPulse 2s ease-in-out infinite;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
}

.ai-copywriting-btn .ai-text {
    font-size: 13px;
    letter-spacing: 0.5px;
    font-weight: 600;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

/* AI脉冲动画效果 */
@keyframes aiPulse {

    0%,
    100% {
        transform: scale(1) rotate(0deg);
        opacity: 1;
    }

    25% {
        transform: scale(1.1) rotate(5deg);
        opacity: 0.8;
    }

    50% {
        transform: scale(1.05) rotate(-3deg);
        opacity: 1;
    }

    75% {
        transform: scale(1.15) rotate(2deg);
        opacity: 0.9;
    }
}

/* 加载状态下的样式 */
.ai-copywriting-btn.is-loading {
    background: linear-gradient(135deg, #9ca3af 0%, #6b7280 100%);
    cursor: not-allowed;
    animation: loadingShimmer 1.5s ease-in-out infinite;
}

.ai-copywriting-btn.is-loading:hover {
    transform: none;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
}

/* 禁用状态下的样式 */
.ai-copywriting-btn:disabled {
    background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%);
    cursor: not-allowed;
    opacity: 0.6;
    transform: none;
}

.ai-copywriting-btn:disabled:hover {
    transform: none;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
}

.ai-copywriting-btn:disabled .ai-icon {
    animation: none;
    opacity: 0.5;
}

/* 加载时的闪烁效果 */
@keyframes loadingShimmer {
    0% {
        background: linear-gradient(135deg, #9ca3af 0%, #6b7280 100%);
    }

    50% {
        background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%);
    }

    100% {
        background: linear-gradient(135deg, #9ca3af 0%, #6b7280 100%);
    }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .ai-copywriting-btn {
        padding: 6px 12px;
        min-width: 80px;
        height: 32px;
    }

    .ai-copywriting-btn .ai-text {
        font-size: 12px;
    }

    .ai-copywriting-btn .ai-icon {
        width: 14px;
        height: 14px;
    }
}

/* 历史文案选择模块样式 */
.history-copywriting-section {
    margin-top: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 12px;
    border: 1px solid #e9ecef;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.section-title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0;
}

.history-icon {
    margin-right: 8px;
    color: #667eea;
}

.refresh-btn {
    color: #667eea;
    font-size: 12px;
}

.refresh-btn:hover {
    color: #5a6fd8;
}

.history-cards-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 12px;
    margin-bottom: 16px;
}

.history-card {
    background: white;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    padding: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.history-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #667eea, #764ba2);
    transform: scaleX(0);
    transition: transform 0.3s ease;
}

.history-card:hover::before {
    transform: scaleX(1);
}

.history-card:hover {
    border-color: #667eea;
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    transform: translateY(-2px);
}

.history-card.selected {
    border-color: #667eea;
    background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.card-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.copywriting-text {
    font-size: 14px;
    line-height: 1.5;
    color: #2c3e50;
    word-break: break-word;
    min-height: 42px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.card-actions {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
}

.use-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 6px;
    padding: 6px 12px;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.use-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.rewrite-btn {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    border: none;
    border-radius: 6px;
    padding: 6px 12px;
    font-size: 12px;
    font-weight: 500;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 4px;
}

.rewrite-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.ai-icon-small {
    animation: aiPulse 2s ease-in-out infinite;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #9ca3af;
}

.empty-icon {
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-text {
    font-size: 14px;
    margin: 0;
}

/* 历史文案分页样式 */
.history-pagination-container {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #e9ecef;
    display: flex;
    justify-content: center;
}

.history-pagination-container :deep(.pagination) {
    display: flex;
    justify-content: center;
}

.history-pagination-container :deep(.el-pagination) {
    --el-pagination-font-size: 13px;
    --el-pagination-button-width: 28px;
    --el-pagination-button-height: 28px;
}

.history-pagination-container :deep(.el-pagination .btn-prev),
.history-pagination-container :deep(.el-pagination .btn-next),
.history-pagination-container :deep(.el-pagination .el-pager li) {
    min-width: 28px;
    height: 28px;
    line-height: 28px;
    margin: 0 2px;
    border-radius: 6px;
    font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .history-cards-container {
        grid-template-columns: 1fr;
    }

    .history-card {
        padding: 12px;
    }

    .card-actions {
        flex-direction: column;
    }

    .use-btn,
    .rewrite-btn {
        width: 100%;
        justify-content: center;
    }
}
</style>